package io.flutter.plugins.webviewflutter;

import android.os.Debug;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.NonNull;

/**
 * 判断字符串是否为空
 * Created by Kevin on 2016/9/27.
 */
public class StringUtils {

    static Pattern pattern2 = Pattern.compile("\n\n");

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmptyString(String str) {
        return str == null || ("null").equals(str) || str.length() == 0 || ("[]").equals(str);
    }

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmptyString(String str) {
        return !isEmptyString(str);
    }

    /**
     * 个位数 补充 0
     *
     * @param s
     * @return
     */
    public static String handleZero(int s) {

        if (s < 10 && s > 0) {
            return "0" + s;
        } else {
            return "" + s;
        }

    }

    public static String delHTMLTag(String htmlStr) {
        if (htmlStr == null) {
            return "";
        }
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
        String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); //过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); //过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); //过滤html标签

        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
        /**返回文本字符串 这个判断和这个方法是对应的 {@link CommonUtil.replaceSomeHtmlTag()} */
        return htmlStr.trim().replace("!@#$%%$#@!!@#$%","");
    }

    public static String deleteSpanTag(String htmlStr) {
        if (htmlStr == null) {
            return "";
        }
        String regEx_spanBegin = "<span[^>]*?>"; //定义span开始节点的正则表达式
        String regEx_spanEnd = "<\\/span>"; //定义span的正则表达式

        Pattern p_span_Begin = Pattern.compile(regEx_spanBegin, Pattern.CASE_INSENSITIVE);
        Matcher m_span_Begin = p_span_Begin.matcher(htmlStr);
        htmlStr = m_span_Begin.replaceAll(""); //过滤span开始标签

        Pattern p_span_End = Pattern.compile(regEx_spanEnd, Pattern.CASE_INSENSITIVE);
        Matcher m_span_End = p_span_End.matcher(htmlStr);
        htmlStr = m_span_End.replaceAll(""); //过滤span结束标签
        return htmlStr.trim(); //返回文本字符串
    }


    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 输出非空String
     *
     * @param mTitle
     * @return
     */
    public static String handleString(String mTitle) {
        if (StringUtils.isEmptyString(mTitle)) {
            return "";
        } else {
            return mTitle;
        }
    }

    /**
     * 输出(String)
     *
     * @param mTitle
     * @return
     */
    public static String handlebracketsString(String mTitle) {
        if (StringUtils.isEmptyString(mTitle)) {
            return "";
        } else {
            return "("+mTitle+")";
        }
    }

    /**
     * 关键字高亮变色
     *
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     * @return 结果SpannableString
     */
    public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
        SpannableString s = new SpannableString(text);
        keyword = escapeExprSpecialWord(keyword);
        text = escapeExprSpecialWord(text);
        if (text.contains(keyword) && !TextUtils.isEmpty(keyword)) {
            try {
                Pattern p = Pattern.compile(keyword);
                Matcher m = p.matcher(s);
                while (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } catch (Exception e) {
                Log.e("StringUtil", e.toString());
            }
        }
        return s;
    }

    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     *
     * @param keyword
     * @return keyword
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (!TextUtils.isEmpty(keyword)) {
            String[] fbsArr = {"\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|"};
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }

    /**
     * 替换段落中的每一个段落中的用户的手动空格
     */
    public static String removeSpaceInStage(@NonNull String string) {
        Matcher matcher2 = pattern2.matcher(string);

        while (matcher2.find()) {
            string = matcher2.replaceAll("\n");
        }

//        Matcher matcher1 = pattern1.matcher(string);
//        while (matcher1.find()) {
//            string = matcher1.replaceAll("\n");
//        }

        return string;

    }

    /**
     * 去除double类型中的无效0
     * @return
     */
    public static String cleanDouble0(double num){
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        return decimalFormat.format(num);
    }

    /**
     * 根据要显示的最大位数，隐藏字符串
     * @param name
     * @param maxShowLength
     * @param replacement
     * @return
     */
    public static String getLongNameString(String name, int maxShowLength, String replacement){
        if(name==null){
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        if(name.length() <= maxShowLength){
            return name;
        }else {
            stringBuilder.append(name, 0, maxShowLength);
            stringBuilder.append(replacement);
            return stringBuilder.toString();
        }
    }

    /**
     * 字符串带默认值显示
     * @param text
     * @param defText
     * @return
     */
    public static String showText(String text, String defText) {
        return TextUtils.isEmpty(text)?defText:text;
    }

    /**
     * 返回text的长度，一个汉字算两个，数字和英文算一个
     *
     * @param text
     * @return
     */
    public static int judgeTextLength(String text) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < text.length(); i++) {
            char item = text.charAt(i);
            if (item < 128) {
                count++;
            } else {
                count += 2;
            }
        }
        return count;
    }

    public static int getWordCount(String s) {
        s = s.replaceAll("[^\\x00-\\xff]", "**");
        int length = s.length();
        return length;
    }
    static Pattern pattern = Pattern.compile("[0-9]*");


    /**
     * 判断字符串是否为数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    /**去除数组空元素*/
    public static String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
        List<String> strList= Arrays.asList(strArray);
        List<String> strListNew=new ArrayList<>();
        for (int i = 0; i <strList.size(); i++) {
            if (strList.get(i)!=null&&!strList.get(i).equals("")){
                strListNew.add(strList.get(i));
            }
        }
        String[] strNewArray = strListNew.toArray(new String[strListNew.size()]);
        return   strNewArray;
    }


    /**
     * 根据视频的url地址获取到文件名
     * 没有文件类型后缀
     * http://etpic.we17.com/video/20210430164733_5915.mp4
     * @param url
     * @return
     */
    public static String getVideoName(String url){
        int startIndex = url.lastIndexOf("/") + 1;
        String name = url.substring(startIndex);
        int endIndex = name.lastIndexOf(".");
        return name.substring(0, endIndex);
    }

    /**
     * 判断是否是字体文件
     * @param url
     * @return
     */
    public static boolean isFontFile(String url){
        if(StringUtils.isEmptyString(url)){
            return false;
        }
        return url.contains(".ttf") || url.contains(".otf")
                || url.contains(".eot") || url.contains(".fon")
                || url.contains(".ttc") || url.contains(".woff")
                || url.contains(".font");
    }
}
